package com.opencloud.system.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.opencloud.common.model.PageParams;
import com.opencloud.common.model.Result;
import com.opencloud.common.security.http.XRestTemplate;
import com.opencloud.common.utils.StringUtils;
import com.opencloud.system.client.model.entity.GatewayIpLimit;
import com.opencloud.system.client.service.IGatewayIpLimitClient;
import com.opencloud.system.service.GatewayIpLimitService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 网关IP访问控制
 *
 * @author: liuyadu
 * @date: 2019/3/12 15:12
 * @description:
 */
@RestController
public class GatewayIpLimitController implements IGatewayIpLimitClient {

    @Autowired
    private GatewayIpLimitService gatewayIpLimitService;
    @Autowired
    private XRestTemplate xRestTemplate;

    @ApiOperation(value = "获取IP策略列表", notes = "获取IP策略列表")
    @GetMapping("/gateway/limit/ip")
    @Override
    public Result<Page<GatewayIpLimit>> getPage(@RequestParam Map<String, Object> map) {
        return Result.ok().data(gatewayIpLimitService.findPage(new PageParams(map)));
    }

    @ApiOperation(value = "获取IP策略", notes = "获取IP策略")
    @GetMapping("/gateway/limit/ip/info")
    @Override
    public Result<GatewayIpLimit> get(@RequestParam("policyId") Long policyId) {
        return Result.ok().data(gatewayIpLimitService.getById(policyId));
    }

    @ApiOperation(value = "添加/修改IP策略", notes = "添加/修改IP策略")
    @PostMapping("/gateway/limit/ip/save")
    @Override
    public Result<Long> save(@RequestBody GatewayIpLimit gatewayIpLimit) {
        gatewayIpLimitService.saveOrUpdate(gatewayIpLimit);
        // 刷新网关
        xRestTemplate.refreshGateway();
        return Result.ok();
    }

    @ApiOperation(value = "移除IP策略", notes = "移除IP策略")
    @PostMapping("/gateway/limit/ip/remove")
    @Override
    public Result remove(@RequestParam("policyId") Long policyId) {
        gatewayIpLimitService.remove(policyId);
        // 刷新网关
        xRestTemplate.refreshGateway();
        return Result.ok();
    }

    @ApiOperation(value = "查询IP策略已绑定API列表", notes = "查询IP策略已绑定API列表")
    @GetMapping("/gateway/limit/ip/api/list")
    @Override
    public Result<Page<GatewayIpLimit>> getApis(@RequestParam("policyId") Long policyId) {
        return Result.ok().data(gatewayIpLimitService.findApiList(policyId));
    }

    @ApiOperation(value = "IP策略绑定API", notes = "一个API只能绑定一个策略")
    @PostMapping("/gateway/limit/ip/save/api")
    @Override
    public Result saveApis(
            @RequestParam("policyId") Long policyId,
            @RequestParam(value = "apiIds", required = false) String apiIds
    ) {
        gatewayIpLimitService.saveApis(policyId, StringUtils.isNotBlank(apiIds) ? apiIds.split(",") : new String[]{});
        xRestTemplate.refreshGateway();
        return Result.ok();
    }
}
